package com.dqyy;

import com.dqyy.entity.Product;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Param;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.core.handle.UploadedFile;
import org.noear.solon.extend.activerecord.annotation.Db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class DemoController {

    private List<Record> hasNumber;

    @Db("db1")
    DbPro db1;
    @Mapping(value = "/searchCode",method = MethodType.GET)
    public ResultEntity searchCode(@Param(defaultValue = "0") String barCode) throws Exception {
        Product product = new Product();
        List<Product> products = product.find("select * from waimai_product where barCode = ?", barCode);
//        List<product> records = db1.queryColumn("select * from waimai_product where barCode = ?", barCode);
        if(products.isEmpty()) throw new Exception("结果为空");
        return ResultEntity.ok("success",products);
    }

    @Mapping(value = "/upload",method = MethodType.POST,multipart=true)
    public ResultEntity upload(UploadedFile file, Context ctx)  {
        try{
            file.isEmpty();
        }catch (Exception e){
            throw new RuntimeException("文件为空");
        }

        List<Product> chongfu  = new ArrayList();
        hasNumber = null;
        try {
            if (!file.getExtension().equalsIgnoreCase("xlsx")) {
                return ResultEntity.no("文件类型错误");
            }
//            String extension = file.getExtension();
//            long time = new Date().getTime();
//            OutputStream outputStream = new FileOutputStream(time+"."+extension);
            XSSFWorkbook sheets = new XSSFWorkbook(file.getContent());
            XSSFSheet sheet = sheets.getSheetAt(0);
            List<Record> selectBarCodeFromWaimaiProduct = db1.find("select `barCode` from waimai_product");
            hasNumber = selectBarCodeFromWaimaiProduct;
            for (Row cells : sheet) {
                if(cells.getRowNum()==0){
                    continue;
                }
                Product product = new Product();

                product.set("areaCode",switchType(cells.getCell(2)));
                product.set("barCode",switchType(cells.getCell(8)));
                product.set("layer",switchType(cells.getCell(4)));
                product.set("productName",switchType(cells.getCell(7)));
                product.set("createTime",LocalDateTime.now());
                product.set("productCode",switchType(cells.getCell(6)));
                product.set("shelfCode",switchType(cells.getCell(3)));
                product.set("locationCode",switchType(cells.getCell(5)));
                String format = (String) switchType(cells.getCell(8));
                boolean b = hasNumber.stream().anyMatch(e -> e.getStr("barCode").equals(format));
                if (b) {
                    chongfu.add(product);
                }else {
                    product.save();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("文件错误打开失败");
        }finally {
            try {
                file.delete();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if(chongfu.isEmpty()) return ResultEntity.ok("添加完成",null);
        return ResultEntity.ok("添加完成,有重复项",chongfu);
    }

    Object switchType(Cell cell){
        switch (cell.getCellType()){
            case NUMERIC:
                DecimalFormat decimalFormat = new DecimalFormat("#");
                return decimalFormat.format(cell.getNumericCellValue());
            case STRING:
                return cell.getStringCellValue();
            case BLANK:
                throw new RuntimeException("第"+(cell.getRowIndex()+1)+"行的主条码为空");
            default:
                throw new RuntimeException("第"+(cell.getRowIndex()+1)+"行的主条码类型不是字符串或整数数字/或为空");
        }
    }

}